from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from eventapp.models import Asset, Event
from timelineapp.models import Timeline, TimelineCategory
from votingapp.models import AssetVotes, EventVotes
from permissionapp.models import Permission
from django.contrib.auth.models import User

def get_user_events(user, approved):
    groups = []
    events = Event.objects.filter(creator=user).filter(approved=approved)
    
    for e in events:
        d = {}
        d["event"] = e.title
        d["assets"] = []
    
        # Gets approved event assets that were created by the user        
        event_assets = Asset.objects.filter(event=e.id).filter(creator=user).filter(approved=approved)
        for a in event_assets:
            d["assets"].append(a)
        groups.append(d)
    return groups

def vote(request, timeline_id):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/user/login?previous=/timelines/%s/vote' % timeline_id)

    user_id = request.user.id
    user = User.objects.get(pk=user_id)
    timeline = Timeline.objects.get(pk=timeline_id)
    event_id = 0
    message = ""
    
    if request.method == 'POST':
            
        if "positive" in request.POST:
            is_positive = True
            if int(request.POST["positive"]) == 0:
                is_positive = False

        if "id" in request.POST:
            eid = request.POST["id"]
            
        if "kind" in request.POST:
            if request.POST["kind"] == "event":
                event = Event.objects.get(pk=eid)
                vote = EventVotes(event=event, user=user, positive=is_positive)
                vote.save()                
                
            else:
                asset = Asset.objects.get(pk=eid)
                print is_positive
                vote = AssetVotes(asset=asset, user=user, positive=is_positive)
                vote.save()
        
        if is_positive:
            message = "Voto a favor registrado com sucesso!"
        else:
            message = "Voto contra registrado com sucesso!"

    # lists elements to vote
    groups = []
    user_groups = []
    
    # Gets user votes
    user_event_votes = EventVotes.objects.filter(user=user) 
    user_asset_votes = AssetVotes.objects.filter(user=user).values_list('asset')
    
    user_events_ids = user_event_votes.values_list('event')

    # Filters events, excluding those that the user has already voted
    events = Event.objects.filter(timeline=timeline_id).exclude(id__in=user_events_ids).filter(approved=0)
    events = events.exclude(id=timeline.cover.id)
    
    for e in events:                    
        d = {}
        d["event"] = e
        d["assets"] = []
        d["voted"] = False
        d["date"] = e.date.strftime("%d/%m/%Y")
        
        d["event_owner"] = False
        if (e.creator == user):
            d["event_owner"] = True
            
        event_assets = Asset.objects.filter(event=e.id).exclude(id__in=user_asset_votes)
        for a in event_assets:
            if (not a.creator == user):
                d["assets"].append(a)
        
        if (d["event_owner"] and d["assets"]) or (not d["event_owner"]):
            groups.append(d)

    for e in user_event_votes:                    
        d = {}
        d["event"] = e.event.title
        d["assets"] = []
        d["voted"] = True

        # Gets event assets and exclude those that the user has already voted       
        event_assets = Asset.objects.filter(event=e.event.id).exclude(id__in=user_asset_votes).filter(approved=0)
        for a in event_assets:
            d["assets"].append(a)
        
        # If no asset needs approval, the event is not displayed 
        if (event_assets):
            groups.append(d)

    return render_to_response('voting_screen.html', locals())

def display_user_events_approved(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/user/login?previous=/user/events/approved')

    user_id = request.user.id
    user = User.objects.get(pk=user_id)
    
    groups = get_user_events(user, 1)
    return render_to_response('user_events_votes.html', locals())

def display_user_events_nonapproved(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/user/login?previous=/user/events/nonapproved')

    user_id = request.user.id
    user = User.objects.get(pk=user_id)
    
    groups = get_user_events(user, 0)    
    return render_to_response('user_events_votes.html', locals())

def select_timeline(request):
    action = "list"
    category =  TimelineCategory.objects.order_by('name')
    selected_category = 0
    timelines = []
    
    if request.method == 'GET':
        if ("timeline_category" in request.GET):
            selected_category = int(request.GET["timeline_category"]) 
    
    if not selected_category:
    
        timelines_list = Timeline.objects.all()
        for t in timelines_list:
            if t.privacy==True:
                try:
                    if request.user.is_authenticated():
                        permission = Permission.objects.get(user=request.user, timeline=t)
                        timelines.append(t)
                except Permission.DoesNotExist:
                    pass
            else:
                timelines.append(t)
        
    else:
        timelines_list = Timeline.objects.filter(categories = selected_category)
        for t in timelines_list:
            if t.privacy==True:
                try:
                    if request.user.is_authenticated():
                        permission = Permission.objects.get(user=request.user, timeline=t)
                        timelines.append(t)
                except Permission.DoesNotExist:
                    pass
            else:
                timelines.append(t)
        
    return render_to_response('timeline_selection.html', locals())
